package com.qf.service.impl;

import com.qf.dao.AdminDao;
import com.qf.dao.UserDao;
import com.qf.dao.impl.UserDaoImpl;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.utils.MailUtils;

import java.sql.SQLException;

/**
 * @author Kuke
 * @date 2022/3/7 17:03
 * 针对前台用户的业务接口实现
 */
public class UserServiceImpl implements UserService {
    @Override
    public boolean checkUser(String username) {
        try {
            //调用前台的用户数据访问接口
            UserDao userDao = new UserDaoImpl() ;
            User user = userDao.selectUserByUsername(username);
            if(user==null){
                //没查到,可以注册
                return  true ;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void registerUser(User user) {
        try {
            UserDao ud = new UserDaoImpl();
            ud.addUser(user);
            System.out.println(user.getCode());
            //上面给数据库中添加数据了
            //给用户的注册邮箱中发送一份邮件,激活用户
            //邮件的工具类
            //参数1:接收邮箱
            //参数2:正文
            //参数3:标题
            MailUtils.sendMail(user.getEmail(),"欢迎会员注册,<a href='http://localhost:8080/Maven_Project_02_war/user?methodName=userActive?code="+user.getCode()+"'>请激活</a>",
                    "用户通过邮箱进行邮件激活") ;
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    public User findUserByCode(String code) {
        try {
            UserDao ud = new UserDaoImpl();
            User user = ud.selectUserByCode(code);
            if (user==null){
                return null;
            }
            user.setState(1);
            ud.updateUser(user);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User  getUserBynameAndPassword(String username, String password) {
        //调用数据访问层,查询用户
        try {
            UserDao userDao = new UserDaoImpl();
            User user = userDao.selectUserByNameAndPassword(username,password);
            if (user!=null){
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
